<?php

namespace app\admin\command;

use Carbon\Carbon;
use fast\Random;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;

use app\admin\model\sport\Batch as BatchModel;
use app\common\library\Batch;


class Cal extends Command
{
    protected $scoreTypes = [
        'middle'  => '中考体育',
        'senior'  => '高考体育',
    ];

    private $_outDir = '/uploads/create';

    // 在CalPersonSalary后运行
    protected function configure()
    {
        $this->setName('cal')
            ->setDescription('计算成绩, 每分钟运行一次');
    }
    
    protected function execute(Input $input, Output $output)
    {
        @ini_set("memory_limit",'-1');
        $stime=microtime(true);


        $curPath = dirname(APP_PATH);
        $outDir = $this->_outDir . "/" . date('Ymd');
        // 生成文件夹
        $outDestDir = $curPath . '/public' . $outDir;
        $this->createDir($outDestDir);

        $batchLib = new Batch();
        $batchModel = BatchModel::where('over_time', 'null')->where('source_filename is not null')->select();
        foreach ($batchModel as $b) {
            // 待分析的xlsx
            // $sourcefilename="/Users/sss020/Downloads/sports_template_1210.xlsx";
            $sourcefilename = $curPath . '/public/' .  $b->source_filename;
            $file = $b->score_header . '_已计算_'.$b->task_id.'.xlsx';
            $saveFilename = $outDir . '/' . $file;
            $filename = $outDestDir . '/' . $file;
            // 结果的xlsx
            // $filename="/Users/sss020/Downloads/sports_1210.xlsx";
            try {
                if ($b->score_type == 'middle') {
                    $batchLib->calMiddleScore($sourcefilename, $filename);
                } else if ($b->score_type == 'senior') {
                    $batchLib->calSeniorScore($sourcefilename, $filename);
                }
                $b->filename = $saveFilename;
                $b->over_time = time();
                $b->success_records = $b->total_records;
                $b->save();
            } catch (Exception $e) {
                print_r($e->getTraceAsString());
            }
        }

        $etime=microtime(true);//获取程序执行结束的时间
        $total=$etime-$stime;   //计算差值
        $output->writeln($total);
        $output->info('cal success');
    }

    private function createDir($destDir)
    {   
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }   
    }

}
